package com.tasks.server;

import java.io.*;
import org.apache.log4j.Logger;

public final class Settings implements Serializable {

	static Logger logger = Logger.getLogger(Settings.class);
	
	private static final long serialVersionUID 	= -4862202076409084249L;
	private static final String defaultFilename = "../properties/tasks.settings";
	
	private int	  	DBType;
	private String 	DBlocation;
	private String 	DBname;	
	private String 	DBusername;
	private String 	DBpassword;
	private static  String 	filename;
	
	public void setDBType(int t)
	{
		DBType = t;
	}
	
	public void setDBlocation(String s)
	{
		DBlocation = s;
	}
	
	public void setDBname(String s)
	{
		DBname = s;
	}
	
	public void setDBusername(String s)
	{
		DBusername = s;
	}
	
	public void setDBpassword(String s)
	{
		DBpassword = s;
	}
	
	public int getDBType()
	{
		return DBType;
	}
	
	public String getDBlocation()
	{
		return DBlocation;
	}
	
	public String getDBname()
	{
		return DBname;
	}
	
	public String getDBusername()
	{
		return DBusername;
	}
	
	public String getDBpassword()
	{
		return DBpassword;
	}
	
	public static Settings load()
	{
		return load(defaultFilename);
	}
	
	public static Settings load(String f)
	{
		filename = f;
		Settings settings = null;
		try 
		{
			ObjectInputStream objstream = new ObjectInputStream(new FileInputStream(filename));
			settings = (Settings) objstream.readObject();		
			objstream.close();
		} 
		catch (Exception e) 
		{
			new ServerException(Settings.class, "load", e);
		}
		return settings;
	}
	
	public void save()
	{
		if(filename != null && filename.length() > 0)
		{
			save(filename);
		}
		else
		{
			save(defaultFilename);
		}
	}
	
	public void save(String f) 
	{
		try
		{
		    ObjectOutputStream objstream = new ObjectOutputStream(new FileOutputStream(f));
		    objstream.writeObject(this);
		    objstream.close();
		}
		catch (IOException e) 
		{
			new ServerException(Settings.class, "save", e);
		}
    }
	
	public String toString()
	{
		String out = "<SETTINGS>\n";
			  out += "  <DBType>"+DBType+"</DBType>\n";
			  out += "  <DBlocation>"+DBlocation+"</DBlocation>\n";
			  out += "  <DBname>"+DBname+"</DBname>\n";
			  out += "  <DBusername>"+DBusername+"</DBusername>\n";
			  out += "  <DBpassword>"+DBpassword+"</DBpassword>\n";
			  out += "  <Filename>"+filename+"</Filename>\n";
			  out += "</SETTINGS>\n";
			
		return out;
	}
}
